<template>
  <div class="mapdiv">
        <div
          class="mapdemo"
          id="mapdemo"
          style="width: 100%; height: 488px"
        ></div>
        <div class="btn" style="position: absolute; right: 50px; top: 50px">
          <div
            class="tool-search"
            :class="{ active: isOpen === true }"
            @click="toggle"
          >
            <span>查询</span>
          </div>
        </div>
        <!-- <identityPop
      v-model="iDialogVisible"
      @click="iDialogShow"
      :position="position"
      :newCenter="newCenter"
      :searchResults="searchResults"
    ></identityPop> -->
        <Popup
          v-model="iDialogVisible"
          :newCenter="newCenter"
          :searchResults="searchResults"
          @overlayTip="mapPop"
          @RemoveOverlayTip="removelayTip"
        />
      </div>
</template>
<script>
// import identityPop from "./identityPop.vue";
import Popup from "./Popup.vue";
import axios from "axios";

import ImageWMS from "ol/source/ImageWMS.js";
import Map from "ol/Map.js";
import View from "ol/View.js";
import XYZ from "ol/source/XYZ";
import { Image as ImageLayer, Tile as TileLayer } from "ol/layer.js";

import { transformExtent } from "ol/proj";
import WFS from "ol/format/WFS";
import GeoJSON from "ol/format/GeoJSON";

import Feature from "ol/Feature";
import { intersects } from "ol/format/filter";

import Point from "ol/geom/Point";

export default {
  components: {
    // identityPop,
    Popup,
  },
  data() {
    return {
      map: null,
      url: "http://192.168.20.28:8000/geoserver/GISZT2022/wms",
      isOpen: false,
      wmsLayer: null,
      geojsonFormat: null,
      searchResults: [],
      iDialogVisible: false,
      newCenter: [],
      position: { X: null, Y: null },

      infos: {
        title: "地图", //功能标题
        desc: "实现点击图斑，查看属性", //功能描述
        methodDesc: [
          '后续加'
        ], //实现原理
      },
    };
  },
  mounted() {
    this.getMapHeight();

    this.initMap();
    this.addLayer();
  },
  methods: {
    getMapHeight() {
      let mapNode = document.querySelector(".mapdemo");
      let Oheight = window.innerHeight - 30;
      mapNode.style.height = Oheight + "px";
      window.onresize = function () {
        let height = window.innerHeight - 30;
        mapNode.style.height = height + "px";
      };
    },
    initMap() {
      const layers = [
        new TileLayer({
          source: new XYZ({
            url: "http://t4.tianditu.com/DataServer?T=vec_w&tk=b9031f80391e6b65bd1dd80dcde1b097&x={x}&y={y}&l={z}",
          }),
        }),
      ];

      this.map = new Map({
        layers: layers,
        target: "mapdemo",
        view: new View({
          projection: "EPSG:4326",
          center: [119, 31],
          zoom: 15,
        }),
      });
    },
    addLayer() {
      const wmsSource = new ImageWMS({
        url: "http://192.168.20.28:8000/geoserver/GISZT2022/wms",
        params: {
          LAYERS: "GISZT2022:huzhouriver",
          VERSION: "1.1.0",
        },
        serverType: "geoserver",
      });
      const wmsLayer = new ImageLayer({
        visible: true,
        source: wmsSource,
        zIndex: 99,
      });
      this.wmsLayer = wmsLayer;

      this.map.addLayer(wmsLayer);
      this.getLayerExent();
      let extent = transformExtent(
        [
          118.82537841796875, 30.1190185546875, 120.93475341796875,
          31.4593505859375,
        ],
        "EPSG:4326",
        this.map.getView().getProjection().getCode()
      );
      this.map.getView().fit(extent, this.map.getSize());
    },
    toggle() {
      this.isOpen = !this.isOpen;
      if (this.isOpen) {
        this.map.on("click", this.mapClick);
      } else {
        this.map.un("click", this.mapClick);
      }
    },
    // 监听地图点击事件
    mapClick(e) {
      // console.log('e',e)
      this.position.X = e.originalEvent.pageX;
      this.position.Y = e.originalEvent.pageY;
      let feature = new Feature({
        geometry: new Point(e.coordinate),
      });
      this.getResult(feature);
    },
    excute(feature) {
      this.geojsonFormat = new GeoJSON();
      let url = "http://192.168.20.28:8000/geoserver/GISZT2022/wfs";
      const geometry = feature.getGeometry();
      //   选中图斑的点设为新的地图中心点
      this.newCenter = geometry.getExtent();

      const geomStr = "the_geom";
      const filter = intersects(geomStr, geometry);
      let featureRequest = new WFS().writeGetFeature({
        //坐标系统
        srsName: "EPSG:4326",
        //命名空间
        featureNS: "",
        //工作区名称
        featurePrefix: "",
        //查询图层
        featureTypes: ["GISZT2022:huzhouriver"],
        outputFormat: "application/json",
        geometryName: "the_geom",
        filter,
      });
      return new Promise((resolve, reject) => {
        fetch(url, {
          method: "POST",
          body: new XMLSerializer().serializeToString(featureRequest),
        })
          .then((response) => {
            return response.json();
          })
          .then((response) => {
            let features = [];
            features = response.features.map((item) => {
              return this.geojsonFormat.readFeature(JSON.stringify(item));
            });
            resolve(features);
          })
          .catch((error) => {
            resolve([]);
            reject(error);
          });
      });
    },
    getResult(feature) {
      this.excute(feature).then((features) => {
        const results = [];
        features.forEach((feature) => {
          const attributes = feature.getProperties();
          delete attributes.geometry;
          let result = {
            geometry: this.geojsonFormat.writeGeometry(feature.getGeometry()),
            attributes,
          };
          results.push(result);
          this.searchResults = results;
          if (this.searchResults.length !== 0) {
            this.iDialogShow();
          }
        });
      });
    },
    async getLayerExent() {
      let extent = await axios
        .request({
          url: "http://192.168.20.28:8000/geoserver/GISZT2022/wms?Request=getCapabilities&service=wms",
          method: "get",
          headers: {
            "Content-Type": "application/xml;charset=UTF-8",
          },
          responseType: "document",
        })
        .then((res) => {
          let extentDom = res.data.getElementsByTagName("BoundingBox")[0];
          const minx = extentDom.getAttribute("minx");
          const miny = extentDom.getAttribute("miny");
          const maxx = extentDom.getAttribute("maxx");
          const maxy = extentDom.getAttribute("maxy");
          let extent = [minx, miny, maxx, maxy];

          return extent;
        });
      return extent;
    },
    // 弹窗
    iDialogShow() {
      this.iDialogVisible = true;

      //   重新确定中心位置
      this.getNewCenter(this.newCenter);
    },
    getNewCenter(center) {
      this.map.getView().animate({
        // 只设置需要的属性即可
        center: center, // 中心点
        zoom: 11, // 缩放级别
        // rotation: 1, // 缩放完成view视图旋转弧度
        duration: 1000, // 缩放持续时间，默认不需要设置
      });
    },
    mapPop(p) {
      this.map.addOverlay(p);
    },
    removelayTip(p){
      this.map.removeOverlay(p);
    }
  },
};
</script>
<style scoped>
.tool-search.active {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}
.tool-search {
  cursor: pointer;
  width: 80px;
  height: 30px;
  border: 1px solid #dcdfe6;
  color: #606266;
  border-radius: 3px;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>